package com.qjc.demo.algorithm.两个线程交替打印;

import java.util.concurrent.Semaphore;

/**
 * @ClassName: Solution
 * @Author: qjc
 * @Date: 2023/8/30 09:31
 */
public class Solution {
    // 两个线程交替打印1，2
    public static void main(String[] args) {
        Semaphore semaphoreA = new Semaphore(1);
        Semaphore semaphoreB = new Semaphore(0);
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    semaphoreA.acquire();
                    System.out.println(1);
                    semaphoreB.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    semaphoreB.acquire();
                    System.out.println(2);
                    semaphoreA.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
